package com.springleaf.common.loader
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	/**
	 * Util class used for loading images into BitmapData or an Array of BitmapData.
	 * 
	 * <pre>
	 * Use as:
	 * 1. loadBitmapData(String) or loadAllBitmapData(Array)
	 * 2. Wait for an Event.COMPLETE (you can also listen for an IO_ERROR event)
	 * 3. get your data using bitmapData or bitmapDataArray
	 * 4. clean (this would be nice)
	 * </pre> 
	 */
	public class BitmapDataLoader extends EventDispatcher
	{
		private var _bitmapData:BitmapData;
		private var _bitmapDataArray:Array;
		
		private var bitmapLoader:Loader;
		private var bitmapRequest:URLRequest;
		private var url:Array;
		private var size:int;
		
		public function BitmapDataLoader() {}
		
		public function loadBitmapData(url:String):void {
			bitmapLoader = new Loader();
			bitmapLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, eventOnComplete);
			bitmapLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, eventOnError);
			
			bitmapRequest = new URLRequest(url);
			bitmapLoader.load(bitmapRequest);
		}
		
		public function loadAllBitmapData(array:Array):void {
			url = array;
			size = array.length;
			_bitmapDataArray = new Array();
			
			loadNext();
		}
		
		private function loadNext():void {
			loadBitmapData(url[url.length - size]);
		}
		
		private function eventOnComplete(event:Event):void {
			var imageLoader:Loader = Loader(event.target.loader);
			var imageBitmap:Bitmap = Bitmap(imageLoader.content);
			
			clean();
			if (url != null) {
				_bitmapDataArray[_bitmapDataArray.length] = imageBitmap.bitmapData;
				if (--size > 0) {
					loadNext();
				} else {
					url = null;
					dispatchEvent(event);
				}
			} else {
				_bitmapData = imageBitmap.bitmapData;
				dispatchEvent(event);
			}
		}
		
		private function eventOnError(event:IOErrorEvent):void {
			clean();
			url = null;
			dispatchEvent(event);
		}
		
		private function clean():void {
			bitmapLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, eventOnComplete);
			bitmapLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, eventOnError);
			bitmapLoader.unload();
		}
		
		public function get bitmapData():BitmapData {
			return _bitmapData;
		}
		
		public function get bitmapDataArray():Array {
			return _bitmapDataArray;
		}
	}
}